<!--
 * @Description: 拉卡拉表单组件
 * @Author: Kerwin
 * @Date: 2024-09-05 18:25:40
 * @LastEditTime: 2024-09-06 13:40:39
 * @LastEditors:  Please set LastEditors
-->

<template>
    <u-tabs :list="tabs" :is-scroll="false" v-model="current" @change="change"></u-tabs>
    <u-form :model="formData" ref="form">
        <view class="section">
            <view class="title">店铺门头照
                <text class="tips"> *请确保图片清晰，文字可辨 </text>
            </view>
            <view class="uploadBox" flex>
                <u-form-item label="" label-width="auto" prop="frontImage" :border-bottom="false">
                    <custom-upload ref="upload1" name="object" :action="uploadUrl" :header="header" max-count="1"
                        :multiple="false" :custom-btn="true" @on-success="uploadSuccess" @on-remove="removeObject"
                        :deletable="!isPreview" index="frontImage" :file-list="formData.frontImage
                            ? [{ url: getImgFullPath(formData.frontImage) }]
                            : []
                            ">
                        <template v-slot:addBtn>
                            <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                <u-icon name="plus" size="80" color="#fff"></u-icon>
                                <view class="des">店铺门头照</view>
                            </view>
                        </template>
                    </custom-upload>
                </u-form-item>
                <u-form-item label="" label-width="auto" prop="cashImage" :border-bottom="false">
                    <custom-upload ref="upload2" name="object" :action="uploadUrl" max-count="1" :custom-btn="true"
                        :deletable="!isPreview" :header="header" @on-success="uploadSuccess" @on-remove="removeObject"
                        index="cashImage" :file-list="formData.cashImage
                            ? [{ url: getImgFullPath(formData.cashImage) }]
                            : []
                            ">
                        <template v-slot:addBtn>
                            <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                <u-icon name="plus" size="80" color="#fff"></u-icon>
                                <view class="des">收银台照</view>
                            </view>
                        </template>
                    </custom-upload>
                </u-form-item>
            </view>
            <view class="uploadBox" flex>
                <u-form-item label="" label-width="auto" prop="insideImage" :border-bottom="false">
                    <custom-upload ref="upload2" :action="uploadUrl" max-count="6" name="object" :custom-btn="true"
                        :deletable="!isPreview" :header="header" @on-success="uploadSuccess" @on-remove="removeObject"
                        index="insideImage" :file-list="formData.insideImage.length > 0
                            ? formData.insideImage.map(item => { return { 'url': getImgFullPath(item) } })
                            : []
                            ">
                        <template v-slot:addBtn>
                            <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                <u-icon name="plus" size="80" color="#fff"></u-icon>
                                <view class="des">店内照片</view>
                            </view>
                        </template>
                    </custom-upload>
                </u-form-item>
            </view>
            <u-form-item required label="经营地址（有营业执照的与营业执照一致）：" label-width="auto" label-position="top"
                prop="shopAdress"><u-input @blur="inputBlur($event, 'shopAdress')" v-model="formData.shopAdress"
                    input-align="left" placeholder="请填写经营地址" :show-confirmbar="false" /></u-form-item>
        </view>
        <view class="section">
            <view class="title">法人代表身份证
                <text class="tips"> *请确保图片清晰，文字可辨，身份证需漏出四角 </text>
            </view>
            <view class="uploadBox" flex>
                <u-form-item label="" label-width="auto" prop="idCardFrontImage" :border-bottom="false">
                    <custom-upload ref="upload1" name="object" :action="uploadUrl" :disabled="false" :header="header"
                        max-count="1" :custom-btn="true" @on-success="uploadSuccess" @on-remove="removeObject"
                        :deletable="!isPreview" index="idCardFrontImage" :file-list="formData.idCardFrontImage
                            ? [{ url: getImgFullPath(formData.idCardFrontImage) }]
                            : []
                            ">
                        <template v-slot:addBtn>
                            <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                <u-icon name="plus" size="80" color="#fff"></u-icon>
                                <view class="des">身份证人像面</view>
                            </view>
                        </template>
                    </custom-upload>
                </u-form-item>
                <u-form-item label="" label-width="auto" prop="idCardBackImage" :border-bottom="false">
                    <custom-upload ref="upload2" name="object" :action="uploadUrl" max-count="1" :custom-btn="true"
                        :deletable="!isPreview" :header="header" @on-success="uploadSuccess" @on-remove="removeObject"
                        index="idCardBackImage" :file-list="formData.idCardBackImage
                            ? [{ url: getImgFullPath(formData.idCardBackImage) }]
                            : []
                            ">
                        <template v-slot:addBtn>
                            <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                <u-icon name="plus" size="80" color="#fff"></u-icon>
                                <view class="des">身份证国徽面</view>
                            </view>
                        </template>
                    </custom-upload>
                </u-form-item>
            </view>

        </view>
        <view class="section">
            <view class="title">银行信息
                <text class="tips"> *请确保图片清晰，文字可辨 </text>
            </view>
            <u-radio-group v-model="formData.jiesuanType" @change="radioGroupChange($event, 'jiesuanType')"
                style="margin-top: 20rpx;">
                <u-radio v-for="(item, index) in radioList" :key="index" :name="item.name" :disabled="item.disabled"
                    label-size="28">
                    {{ item.name }}
                </u-radio>
            </u-radio-group>
            <view class="links" v-show="isFfrjs" style="margin-top: 30rpx;">
                <template v-for="(item, index) in protocolTemplates" :key="index">
                    <text v-if="index === 3" @click="downloadByUrl(item.url, item.name)">《{{
                        item.name }}》</text>
                </template>
            </view>
            <view class="uploadBox" flex>
                <u-form-item v-if="isFfrjs" label="" label-width="auto" prop="idCardFrontImage2" :border-bottom="false">
                    <custom-upload ref="upload1" name="object" :action="uploadUrl" :header="header" max-count="1"
                        :deletable="!isPreview" :custom-btn="true" @on-success="uploadSuccess" @on-remove="removeObject"
                        index="idCardFrontImage2" :file-list="formData.idCardFrontImage2
                            ? [{ url: getImgFullPath(formData.idCardFrontImage2) }]
                            : []
                            ">
                        <template v-slot:addBtn>
                            <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                <u-icon name="plus" size="80" color="#fff"></u-icon>
                                <view class="des">非法人身份证人像面</view>
                            </view>
                        </template>
                    </custom-upload>
                </u-form-item>
                <u-form-item v-if="isFfrjs" label="" label-width="auto" prop="idCardBackImage2" :border-bottom="false">
                    <custom-upload ref="upload2" name="object" :action="uploadUrl" max-count="1" :custom-btn="true"
                        :deletable="!isPreview" :header="header" @on-success="uploadSuccess" @on-remove="removeObject"
                        index="idCardBackImage2" :file-list="formData.idCardBackImage2
                            ? [{ url: getImgFullPath(formData.idCardBackImage2) }]
                            : []
                            ">
                        <template v-slot:addBtn>
                            <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                <u-icon name="plus" size="80" color="#fff"></u-icon>
                                <view class="des">非法人身份证国徽面</view>
                            </view>
                        </template>
                    </custom-upload>
                </u-form-item>
                <u-form-item v-if="isFfrjs" label="" label-width="auto" prop="zjsqAgreementImage" :border-bottom="false">
                    <custom-upload ref="upload2" :action="uploadUrl" name="object" max-count="1" :custom-btn="true"
                        :header="header" :deletable="!isPreview" @on-success="uploadSuccess" @on-remove="removeObject"
                        index="zjsqAgreementImage" :file-list="formData.zjsqAgreementImage
                            ? [{ url: getImgFullPath(formData.zjsqAgreementImage) }]
                            : []
                            ">
                        <template v-slot:addBtn>
                            <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                <u-icon name="plus" size="80" color="#fff"></u-icon>
                                <view class="des">非法人清算委托协议</view>
                            </view>
                        </template>
                    </custom-upload>
                </u-form-item>
            </view>
            <view class="uploadBox" flex>
                <u-form-item label="" label-width="auto" prop="bankcardImage" :border-bottom="false">
                    <custom-upload ref="upload1" name="object" :action="uploadUrl" :header="header" max-count="1"
                        :custom-btn="true" :deletable="!isPreview" @on-success="uploadSuccess" @on-remove="removeObject"
                        index="bankcardImage" :file-list="formData.bankcardImage
                            ? [{ url: getImgFullPath(formData.bankcardImage) }]
                            : []
                            ">
                        <template v-slot:addBtn>
                            <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                <u-icon name="plus" size="80" color="#fff"></u-icon>
                                <view class="des">银行卡号面</view>
                            </view>
                        </template>
                    </custom-upload>
                </u-form-item>
                <u-form-item label="" label-width="auto" prop="bankcardBackImage" :border-bottom="false">
                    <custom-upload ref="upload1" name="object" :action="uploadUrl" :header="header" max-count="1"
                        :custom-btn="true" :deletable="!isPreview" @on-success="uploadSuccess" @on-remove="removeObject"
                        index="bankcardBackImage" :file-list="formData.bankcardBackImage
                            ? [{ url: getImgFullPath(formData.bankcardBackImage) }]
                            : []
                            ">
                        <template v-slot:addBtn>
                            <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                <u-icon name="plus" size="80" color="#fff"></u-icon>
                                <view class="des">银行卡背面</view>
                            </view>
                        </template>
                    </custom-upload>
                </u-form-item>
            </view>

            <u-form-item required label="银行卡号：" label-width="auto" prop="bankcardNo"><u-input
                    @blur="inputBlur($event, 'bankcardNo')" v-model="formData.bankcardNo" input-align="right"
                    placeholder="请填写银行卡号" :show-confirmbar="false" /></u-form-item>
            <u-form-item required label="开户行：" label-width="auto" prop="bankBranch"><u-input
                    @blur="inputBlur($event, 'bankBranch')" v-model="formData.bankBranch" input-align="right"
                    placeholder="请填写开户行（具体的分行）" :show-confirmbar="false" /></u-form-item>
            <u-form-item required label="邮箱：" label-width="auto" prop="bankcardEmail"><u-input
                    v-model="formData.bankcardEmail" @blur="inputBlur($event, 'bankcardEmail')" input-align="right"
                    placeholder="请填写邮箱（用于接收账单信息）" :show-confirmbar="false" /></u-form-item>
            <u-form-item required label="银行卡本人手机号：" label-width="auto" prop="bankcardPhone" :border-bottom="false"><u-input
                    v-model="formData.bankcardPhone" @blur="inputBlur($event, 'bankcardPhone')" input-align="right"
                    placeholder="请填写银行卡本人手机号" :show-confirmbar="false" /></u-form-item>
            <!-- <u-form-item required label="让利比例(%)：" label-width="auto" :border-bottom="false" prop="rate"><u-input
            v-model="formData.rate" @blur="inputBlur($event, 'rate')" input-align="right" placeholder="请填写让利比例"
            :show-confirmbar="false" /></u-form-item> -->
        </view>
        <view class="section" v-if="current === 1">
            <view class="title">盖章资料扫描件
                <text class="tips"> *请确保图片清晰，文字可辨 </text>
            </view>
            <view class="links">
                <template v-for="(item, index) in protocolTemplates" :key="index">
                    <text v-if="index < 3" @click="downloadByUrl(item.url, item.name)">《{{
                        item.name }}》</text>
                </template>

            </view>
            <view class="uploadBox" flex>
                <u-form-item v-if="current !== 0" label="" label-width="auto" prop="shrzAgreementImage"
                    :border-bottom="false">
                    <custom-upload ref="upload1" name="object" :action="uploadUrl" :header="header" max-count="1"
                        :deletable="!isPreview" :custom-btn="true" @on-success="uploadSuccess" @on-remove="removeObject"
                        index="shrzAgreementImage" :file-list="formData.shrzAgreementImage
                            ? [{ url: getImgFullPath(formData.shrzAgreementImage) }]
                            : []
                            ">
                        <template v-slot:addBtn>
                            <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                <u-icon name="plus" size="80" color="#fff"></u-icon>
                                <view class="des">商户入驻协议</view>
                            </view>
                        </template>
                    </custom-upload>
                </u-form-item>
                <u-form-item v-if="current !== 0" label="" label-width="auto" prop="qfjsAgreementImage"
                    :border-bottom="false">
                    <custom-upload ref="upload2" :action="uploadUrl" name="object" max-count="1" :custom-btn="true"
                        :header="header" :deletable="!isPreview" @on-success="uploadSuccess" @on-remove="removeObject"
                        index="qfjsAgreementImage" :file-list="formData.qfjsAgreementImage
                            ? [{ url: getImgFullPath(formData.qfjsAgreementImage) }]
                            : []
                            ">
                        <template v-slot:addBtn>
                            <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                <u-icon name="plus" size="80" color="#fff"></u-icon>
                                <view class="des">清分结算授权委托书</view>
                            </view>
                        </template>
                    </custom-upload>
                </u-form-item>
                <u-form-item v-if="isFfrjs" label="" label-width="auto" prop="shfzAgreementImage" :border-bottom="false">
                    <custom-upload ref="upload2" :action="uploadUrl" name="object" max-count="1" :custom-btn="true"
                        :header="header" :deletable="!isPreview" @on-success="uploadSuccess" @on-remove="removeObject"
                        index="shfzAgreementImage" :file-list="formData.shfzAgreementImage
                            ? [{ url: getImgFullPath(formData.shfzAgreementImage) }]
                            : []
                            ">
                        <template v-slot:addBtn>
                            <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                <u-icon name="plus" size="80" color="#fff"></u-icon>
                                <view class="des">商户分账服务开通申请登记表</view>
                            </view>
                        </template>
                    </custom-upload>
                </u-form-item>
            </view>

        </view>
        <view class="section remark">
            <view class="red">
                备注： <br>
                1.信息填写完成后请在1-2个工作日后扫描下方二维码（将二维码保存到手机）<br>
                2.分别进行微信和支付宝认证（认证方式:微信和支付宝分别扫描对应的二维码，选择商户号，确定即可）
                <!-- 3.如有不清楚的地方，请咨询微信：lelex777(鲜老师) -->
            </view>
            <image class="img" src="https://image.blacksilverscore.com/uploads/c2131a39-c23d-4b0c-af48-3900f5de2103.jpg"
                mode="widthFix" />
            <image class="img" src="https://image.blacksilverscore.com/uploads/8d82cccf-3bf8-4254-8691-9cebf1f1c893.jpg"
                mode="widthFix" />
        </view>
        <view class="protocol" v-if="!isPreview">
            <u-checkbox-group>
                <u-checkbox v-model="agree">
                    <text>同意资料申报由黑银工作人员办理</text>
                </u-checkbox>
            </u-checkbox-group>
        </view>
        <u-button type="primary" style="margin:0 30rpx" @click="submit" v-if="!isPreview">提交审核</u-button>
    </u-form>
</template>


<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { baseApi, powerBankApi, userApi, productApi } from '@/api';
import { checkLoginState, getImgFullPath } from '@/utils/index';
import { useUserStore } from '@/store';
import customUpload from "../../components/custom-upload/custom-upload.vue";
import { getCookie } from '@/utils/common';
import { route } from '../../../utils/common';
import { UPLOADURL as uploadUrl } from "@/common/config";

const userStore = useUserStore();

const props = defineProps<{
    isPreview: boolean;
}>();

const tabs = [
    { name: '个体商户', id: 1 },
    { name: '企业商户', id: 2 }
];
const current = ref(0);
const change = (index: number) => handler('shopType', index);
const form = ref();

interface FormData {
    paymentChannel: string;
    accessStatus: string;
    shopType: string;
    frontImage: string;
    cashImage: string;
    insideImage: string[];
    shopAdress: string;
    idCardFrontImage: string;
    idCardBackImage: string;
    idCardFrontImage2: string;
    idCardBackImage2: string;
    zjsqAgreementImage: string;
    bankcardImage: string;
    bankcardBackImage: string;
    bankcardNo: string;
    bankBranch: string;
    bankcardEmail: string;
    bankcardPhone: string;
    rate: string;
    jiesuanType: string;
    qfjsAgreementImage: string;
    shrzAgreementImage: string;
    shfzAgreementImage: string;
}

const formData = reactive<FormData>({
    paymentChannel: '',
    accessStatus: '',
    shopType: '',
    frontImage: '',
    cashImage: '',
    insideImage: [],
    shopAdress: '',
    idCardFrontImage: '',
    idCardBackImage: '',
    idCardFrontImage2: '',
    idCardBackImage2: '',
    zjsqAgreementImage: '',
    bankcardImage: '',
    bankcardBackImage: '',
    bankcardNo: '',
    bankBranch: '',
    bankcardEmail: '',
    bankcardPhone: '',
    rate: '',
    jiesuanType: '法人结算',
    qfjsAgreementImage: '',
    shrzAgreementImage: '',
    shfzAgreementImage: ''
});

const rules = reactive({
    shopAdress: [
        { required: true, message: '请填写经营地址', trigger: ['change', 'blur'] }
    ],
    bankcardNo: [
        { required: true, message: '请填写银行卡卡号', trigger: ['change', 'blur'] }
    ],
    bankBranch: [
        { required: true, message: '请填写银行卡开户行', trigger: ['change', 'blur'] }
    ],
    bankcardEmail: [
        { required: true, message: '请填写银行卡邮箱', trigger: ['change', 'blur'] }
    ],
    bankcardPhone: [
        { required: true, message: '请填写银行卡手机号', trigger: ['change', 'blur'] }
    ],
    rate: [
        { required: true, message: '请填写让利比例', trigger: ['change', 'blur'] }
    ]
});

const tempFormData = reactive<Partial<FormData>>({});

const header = reactive({
    Authorization: `Bearer ${uni.getStorageSync('accessToken') || getCookie('HYToken') || ''}`
});

const CHECKSTATUS = {
    DEFAULT: 0,
    CHECK_WILL: 1,
    CHECK_ING: 10,
    CHECK_SUCCESS: 20,
    CHECK_FAIL: 21,
    CHECK_DONE: 22
};

const CHECKTIPS = {
    [CHECKSTATUS.DEFAULT]: '',
    [CHECKSTATUS.CHECK_WILL]: '待审核，后续相关工作人员可能会联系您，请保持电话畅通！',
    [CHECKSTATUS.CHECK_ING]: '资料审核中，请您耐心等待！',
    [CHECKSTATUS.CHECK_SUCCESS]: '审核同意，资料入网中！',
    [CHECKSTATUS.CHECK_FAIL]: '审核拒绝，请您按照相关工作人员的辅助重新提交资料！',
    [CHECKSTATUS.CHECK_DONE]: '入网已完成，您可测试支付！'
};

const tips = ref('');

function getTips(status: number): string {
    return CHECKTIPS[status] || '';
}


function uploadSuccess(data: any, index: any, lists: any, name: keyof FormData) {
    handler(name, data.data);
}

function handler(name: keyof FormData, data: any) {
    if (props.isPreview) {
        uni.showToast({ icon: "none", title: "预览模式，不可修改数据！" });
        return;
    }
    const id = getIdByName(name);
    const executor = id ? externalUpdate : externalAdd;
    let fieldValue = data;
    if (formData[name] instanceof Array) {
        if (!tempFormData[name]) {
            (tempFormData[name] as string[]) = [];
        }
        (tempFormData[name] as string[]).push(data);
        fieldValue = JSON.stringify(tempFormData[name]);
    } else {
        tempFormData[name] = data;
    }
    executor({ id, fieldName: name, fieldValue });
}

function inputBlur(e: any, name: keyof FormData) {
    handler(name, e);
}

function removeObject(index: number, lists: any, name: keyof FormData) {
    if (typeof formData[name] === 'string') {
        externalUpdate({ id: getIdByName(name), fieldName: name, fieldValue: '' });
        formData[name] = '';
        tempFormData[name] = '';
    } else {
        (tempFormData[name] as string[]).splice(index, 1);
        externalUpdate({ id: getIdByName(name), fieldName: name, fieldValue: JSON.stringify(tempFormData[name]) });
    }
}

const shopId = ref('');

async function externalAdd(obj: { fieldName: keyof FormData; fieldValue: string; shopId: string }) {
    const { data } = await productApi.externalAdd({ ...obj, shopId: shopId.value });
    getShopExternals(false);
}

async function externalUpdate(obj: { id: number; fieldName: keyof FormData; fieldValue: string; shopId: string }) {
    const { data } = await productApi.externalUpdate({ ...obj, shopId: shopId.value });
}

interface ShopExternal {
    fieldName: keyof FormData;
    fieldValue: string;
    id: number;
    shopId: number;
}

const shopExternals = ref<ShopExternal[]>([]);

async function getShopExternals(flag = true) {
    if (!shopId.value) return;
    uni.showLoading();
    const { data } = await productApi.getShopInfo({ id: shopId.value, detail: true }).finally(() => {
        uni.hideLoading();
    });
    shopExternals.value = data.shopExternals;
    if (!flag) return;
    getValueByName(formData, tempFormData, shopExternals);
    current.value = Number(formData.shopType);
    isFfrjs.value = formData.jiesuanType === '非法人结算';
    tips.value = getTips(formData.accessStatus);
}

function getIdByName(name: keyof FormData): number | null {
    const external = shopExternals.value.find(item => item.fieldName === name);
    return external ? external.id : null;
}

function getValueByName(formData: FormData, tempFormData: Partial<FormData>, shopExternals: { value: ShopExternal[] }) {
    for (const [key, value] of Object.entries(formData)) {
        const external = shopExternals.value.find(item => item.fieldName === key);
        if (external) {
            if (typeof value === 'string') {
                formData[key as keyof FormData] = external.fieldValue;
                tempFormData[key as keyof FormData] = external.fieldValue;
            } else {
                formData[key as keyof FormData] = JSON.parse(external.fieldValue);
                tempFormData[key as keyof FormData] = JSON.parse(external.fieldValue);
            }
        }
    }
}

const radioList = [
    { name: '法人结算', disabled: false },
    { name: '非法人结算', disabled: false }
];
const isFfrjs = ref(false);
const radioGroupChange = (e: string, name: keyof FormData) => {
    isFfrjs.value = e === radioList[1].name;
    handler(name, e);
};

function submit() {
    form.value.validate((valid: boolean) => {
        if (valid) {
            const data = { ...formData, ...tempFormData };
            handler('accessStatus', CHECKSTATUS.CHECK_WILL);
            uni.showToast({ title: '提交成功' });
        }
    });
}

const isApp = ref(false);
</script>


<style lang="scss" scoped></style>
